<?php

namespace app\api\controller\xilumarket;


use app\common\controller\Api;
use app\common\model\xilumarket\Third;
use function fast\array_get;

class Pay extends Api
{
    protected $noNeedRight = ['*'];

    /**
     * 收银台
     */
    public function pre_pay_order(){
        $order_id = $this->request->post('order_id');
        $order = \app\common\model\xilumarket\Order::get($order_id);
        if($order->state != 0){
            $this->error("当前订单不可支付");
        }
        $this->success('',$order);
    }

    /**
     * 支付
     */
    public function pay()
    {
        $params = $this->request->param('');
        $platform = array_get($params, 'platform', 'wxmini');
        $order_id = array_get($params, 'order_id');
        $pay_type = array_get($params, 'pay_type');
        if (!$order_id || !$pay_type) {
            $this->error('参数错误');
        }
        $config = \app\common\model\xilumarket\Config::getMyConfig('wxpayment');
        if (!$config || !$config['mch_id'] || !$config['mch_key']) {
            $this->error("请正确配置微信商户信息");
        }
        $type = array_get($params, 'type','order');
        switch ($type) {
            case 'order':
                $orderinfo = \app\common\model\xilumarket\Order::get($order_id);
                if ($platform !== $orderinfo['platform']) {
                    $this->error("下单端与支付端不一致");
                }
                if ($orderinfo && $orderinfo->pay_status == '1') {
                    $this->error("不要重复支付");
                }
                $orderinfo->pay_type = $pay_type;
                $orderinfo->order_trade_no = 'CO' . date('YmdHis') . mt_rand(10, 9999);
                $orderinfo->save();
                $order_no = $orderinfo['order_trade_no'];
                $pay_price = $orderinfo['pay_price'];
                $notify_url = request()->domain().'/addons/xilumarket/weixin_mini/notify/table/order';
                break;
            default:
                $this->success("当前模块不支持支付");
        }

        if ($pay_type == 1) {
            #微信支付
            #查看是什么平台订单
            if ($platform == 'wxmini') {
                $openid = Third::where('user_id', $this->auth->id)->where('platform', $platform)->value('openid');
                $orderinfo = [
                    'body' => '购买商品',
                    'order_no' => $order_no,
                    'pay_price' => $pay_price,
                    // 'pay_price' =>  0.01,
                    'notify_url' => $notify_url,
                    'openid' => $openid,
                ];
                $wx = new \addons\xilumarket\controller\WeixinMini();
                $result3 = $wx->union_order($orderinfo);
                if ($result3) {
                    $this->success('创建微信订单成功', $result3);
                } else {
                    $this->error('创建微信订单失败');
                }
            }

        } else {
            $this->success("暂不支持当前支付类型");
        }


    }

}